<template>
  <div>
    <img :src="qrCodeUrl" class="w-30 h-30" />
    <br />
    <van-button @click="downloadFile">下载二维码</van-button>
  </div>
</template>

<script setup lang="ts">
const qrCodeUrl =
  'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=gQH-7zwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyVDA1WFZteFFmYUQxcW5fZnh6Y1AAAgQXOzFjAwSAhB4A';
async function downloadFile() {
  onUpLoad(qrCodeUrl.substr('https://mp.weixin.qq.com/'.length));
}
async function onUpLoad(file) {
  const options = {
    headers: {
      'Access-Control-Allow-Origin': '*',
    },
  };
  let data = await fetch('/wxapi' + file, options)
    .then((response) => response.blob())
    .then((res) => {
      const { type } = res;
      let blob = new Blob([res], { type });
      downloadBlob(blob, 'qr_code');
    });
  return data;
}
function downloadBlob(blob, fileName) {
  try {
    const href = window.URL.createObjectURL(blob);
    const navigator = window.navigator as any;
    if (navigator.msSaveBlob) {
      navigator.msSaveBlob(blob, fileName);
    } else {
      const downloadElement = document.createElement('a');
      downloadElement.href = href;
      downloadElement.target = '_blank';
      downloadElement.download = fileName;
      document.body.appendChild(downloadElement);
      downloadElement.click(); // 点击下载
      document.body.removeChild(downloadElement); // 下载完成移除元素
      window.URL.revokeObjectURL(href); // 释放掉blob对象
    }
  } catch (e) {
    console.log('下载失败');
  }
}
</script>

<style scoped></style>
